package com.xius.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.xius.common.ApiController;
import com.xius.common.ApiErrorCode;
import com.xius.common.PassToken;
import com.xius.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

@RestController
@RequestMapping("/img/file")
public class FileController extends ApiController {
    @Value("${web.upload-path}")
    private String webUpload;
    @PassToken
    @PostMapping("/multipartFile")
    public R projectWorkerAdd(String path, MultipartFile multipartFile) {

        File file;
        try {
            if(!StrUtil.isEmpty(path)){
                path = path+"\\";
            }else {
                path="";
            }
            file = FileUtil.writeFromStream(multipartFile.getInputStream(), webUpload +path+ multipartFile.getOriginalFilename());
        } catch (IOException e) {
            //e.printStackTrace();
            return failed(ApiErrorCode.UPLOADERROR);
        }
        String savePath = file.getPath().replace(webUpload, "");
        HashMap<String, Object> map = new HashMap<>();
        map.put("path",savePath.trim());
        return success(map);
    }
}
